<template>
  <div class="jiangJinBody">
    <basic-container>
      <navigation :sign="{a:false,b:false,c:true,d:false,e:false}"></navigation>
      <div v-if="ymLoad" class="duiQitishi">
        <div class="tiShiTu">
          <img src="/images/qita/tishi.png" width="300">
        </div>
        <div class="tiShi">
          <div><b>您现在不是任何部门的奖金管理人员，无法进行人员分组维护的操作</b></div>
          <div class="font18 mt10">您可以通知系统管理员，为您设置具体的奖金管理部门！</div>
        </div>
      </div>
      <div v-else>
      <div class="anAnAn" style="padding-bottom: 0px">
        <div class="flex justifyContentSpaceBetween">
          <div class="tabletext">人员分组维护</div>
        </div>
        <div>
          <el-row >
            <el-col :span="18">
              <el-form :inline="true" :model="dataForm" class="form-inline">
                <el-form-item label="负责部门">
                  <el-select v-model="deptId" placeholder="请选择负责部门" class="xiaLa" style="width: 300px" >
                    <el-option v-for="(item,index) in fzbmData" :key="index" :label="item.deptName" :value="item.deptId"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="员工子组">
                  <el-select :clearable="true" v-model="dataForm.ryZz" placeholder="请选择" style="width:150px">
                    <el-option v-for="(item,index) in userZzOptions " :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="岗位层级">
                  <el-select :clearable="true" v-model="dataForm.ryZwjbbh" placeholder="请选择" style="width:150px">
                    <el-option v-for="(item,index) in userZjOptions " :key="index" :label="item.label" :value="item.label">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="岗位">
                  <el-input v-model="dataForm.ryZhiwei" placeholder="职位" style="width:150px"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" plain class="marginLeft" @click="switchDepartment">检索</el-button>
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="6">
              <div style="padding:20px 0;">
                <el-button type="primary" plain icon="el-icon-refresh" @click="refresh" style="float: right" v-if="deptId != ''">刷新</el-button>
                <el-button type="primary" plain @click="btnAllocationXxPz" style="float: right;margin-right: 10px" v-if="deptId != ''">系数详细配置</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <el-row>
        <el-col :span="8">
          <div class="user__main boxsty filter-container">
            <div class="mb10">
              <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
            </div>
            <div class="avue-crud" style="height:calc(100vh - 470px);">
              <el-tree :data="ryData" ref="tree" show-checkbox node-key="deptId" :props="defaultProps" :default-expanded-keys="idArr"  @check="handleSelectionChange" :filter-node-method="filterNode"></el-tree>
            </div>
          </div>
        </el-col>
        <el-col :span="2">
          <div class="box-card anDuiQi" style="height:50vh">
            <div class="mb10">
              <el-button type="primary" @click="leftMove()" class="fenZuAn"><i class="el-icon-arrow-left" style="font-size:30px;"></i></el-button>
            </div>
            <div>
              <el-button type="primary" @click="rightMove()" class="fenZuAn"><i class="el-icon-arrow-right" style="font-size:30px;"></i></el-button>
            </div>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="user__main boxsty filter-container">
            <div class="mb10">
              <span>人员分组</span>
              <!-- <el-button type="warning" v-if="deptId != ''" plain @click.stop="btnAllocationFz('all')" class="ml10">配置系数</el-button> -->
              <el-button type="warning" v-if="deptId != ''" plain @click="add_grouping($event)" class="ml10">添加分组</el-button>
            </div>
            <div class="avue-crud" style="height:calc(100vh - 470px);">
              <el-collapse v-model="activeName" accordion v-for="(item,index)  in fzData" @change="queryXh(item.id,index)" :key="index">
                <el-collapse-item :name="index">
                  <template slot="title">
                    <div class="collapseBox">
                      <div class="flex justifyContentSpaceBetween">
                        <div>
                          <el-radio v-model="radio" :label="index" @click.stop.native="grouping(item.id,index)" style="margin-right:0px;">{{ '' }}</el-radio>
                          <span>{{ item.ryfzMc }}（系数:{{ item.fzXs.toFixed(2) }}）--{{ item.sl }} 人</span>
                        </div>
                        <div style="margin-right:3px;">
                          <!-- <el-button type="primary" plain @click.stop="btnAllocationFz(item.id)">配置系数</el-button> -->
                          <el-button type="primary" plain @click="addOtherPerson($event,item,index)">增加外部人员</el-button>
                          <el-button type="primary" plain @click="add_grouping($event,item.id)">修改分组</el-button>
                          <el-button type="danger" plain @click="deleteHandle($event,item.id)">删除分组</el-button>
                        </div>
                      </div>
                    </div>
                  </template>
                  <div class="noBorder">
                      <el-table :data="item.tableData" @selection-change="handleSelectionChangezdyfz"
                                class="avue-crud" border v-loading="dataListLoading">
                      <el-table-column type="selection" header-align="center" align="center" width="55"></el-table-column>
                      <el-table-column prop="ryCode" header-align="center" align="center" min-width="100" label="员工编号"></el-table-column>
                      <el-table-column prop="ryName" header-align="center" align="center" label="姓名" min-width="120"></el-table-column>
                      <!-- <el-table-column prop="config02" header-align="center" align="center" label="员工考核基础分"></el-table-column>
                      <el-table-column prop="config03" header-align="center" align="center" label="个人考核分级"></el-table-column> -->
                      <el-table-column header-align="center" align="center" label="操作" min-width="110">
                        <template slot-scope="scope">
                          <el-button type="primary" plain size="small" @click="btnAllocation(scope.row.ryCode)">配置系数</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </div>
        </el-col>
      </el-row>
      </div>
      <!-- 添加分组 -->
      <tableForm ref="tableForm" @refreshDataList="refresh"></tableForm>
      <!-- 配置 -->
      <Tallocation v-if="allocationVisible" ref="tallocation" v-on:refresh="refreshby"></Tallocation>
      <!-- 配置_分组_全部 -->
      <TallocationFzQb v-if="allocationVisibleFzQb" ref="tallocationFzQb" v-on:refresh="refresh"></TallocationFzQb>
      <!-- 系数详细配置 -->
      <TallocationXxPz v-if="allocationVisibleXxPz" ref="tallocationXxPz" v-on:refresh="refresh"></TallocationXxPz>
      <!-- 外部人员 -->
      <per-selection v-if="perSelectionVisible" ref="perselection" v-on:refresh="refreshby"></per-selection>
    </basic-container>
  </div>
</template>

<script>
/*!
 * 绩效考核-人员分组维护主页面
 *
 * @author zmk
 * @date 2021-08-03 10:11:35
 */
import {remote as remoteDict} from '@/api/admin/dict';
import {getRyfzbList, delObj, getDeptList} from '@/api/jiangjin/jiangjinryfzb'
import {insertRymxbList, getFzList, updateRymxbList, getOtherRyfzmx} from '@/api/jiangjin/jiangjinryfzmxb'
import {fetchListfy} from '@/api/jiangjin/jiangjinryxxb'
import tableForm from './jiangjinryfzb-form'
import {getJiangJinBm} from '@/api/admin/dept'
import Tallocation from "../jiangjinryxxb/codeRyxx";
import TallocationFzQb from "../jiangjinryxxb/xxPz";
import TallocationXxPz from "../jiangjinryxxb/xiangxiPz"
import perSelection from './personnelSelectionTwo'

import {mapGetters} from 'vuex'

export default {
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dataForm: {
        ryZz: '',
        ryZwjbbh: '',
        ryZhiwei: ''
      },
      userZjOptions: [], // 职级
      userZzOptions: [], // 人员子组
      filterText: '',
      fzData: [],//分组list
      ryData: [],//人员list
      deptId: '',//负责部门ID
      deptName: '',//负责部门名称
      radio: 0,
      multipleSelection: [],
      multipleSelectionfz: [],
      activeName: '',//手风琴name控制
      allocationVisible: false,
      allocationVisibleFzQb: false,
      allocationVisibleXxPz: false,
      perSelectionVisible: false,
      fzbmData: [],
      ymLoad:false,
      dataListLoading: false,
      idArr:[]
    }
  },
  components: {
    tableForm,
    Tallocation,
    TallocationFzQb,
    TallocationXxPz,
    perSelection,
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
  },
  mounted() {
    this.getJiangJinJg()
  },
  computed: {
    ...mapGetters(['permissions'])
  },
  methods: {

    //系数配置_个人
    btnAllocation(code) {
      this.allocationVisible = true;
      this.$nextTick(() => {
        this.$refs.tallocation.init(code, this.deptId)
      })
    },
    //系数配置_分组_全部
    btnAllocationFz(code) {
      if (code == "all") {
        if(this.fzData.length==0){
          this.btnAllocationFzs(code,  this.deptId,"");
        }else{
          getFzList(this.fzData[0].id).then(response => {
            if(response.data.data.length>0){
              this.btnAllocationFzs(code,  this.deptId,response.data.data[0].ryCode);
            }else{
              this.btnAllocationFzs(code,  this.deptId,"");
            }
          })
        }
      } else {
        getFzList(code).then(response => {
          if(response.data.data.length>0){
            this.btnAllocationFzs(code,  this.deptId,response.data.data[0].ryCode);
          }else{
            this.btnAllocationFzs(code,  this.deptId,"");
          }
        })
      }
    },
    btnAllocationFzs(code,deptId,info){
      this.allocationVisibleFzQb = true;
      this.$nextTick(() => {
        this.$refs.tallocationFzQb.init(code, deptId,info)
      })
    },
    //系数详细配置
    btnAllocationXxPz() {
      this.allocationVisibleXxPz = true;
      this.$nextTick(() => {
        this.$refs.tallocationXxPz.init({deptId: this.deptId, deptName: this.deptName})
      })
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //左移动
    leftMove() {
      if (this.multipleSelectionfz.length == 0) {
        this.$notify.closeAll();
        this.$notify.error("没有可移动项人员")
        return;
      }

      updateRymxbList(this.multipleSelectionfz).then(data => {
        if (data.data.code == 0) {
          this.$notify.closeAll();
          this.$notify.success('操作成功')
          this.multipleSelectionfz = [];
          this.refreshby();
        } else {
          this.$notify.closeAll();
          this.$notify.error("操作失败")
        }
      }).catch(() => {
        this.$notify.closeAll();
        this.$notify.error("操作失败")
      });
    },
    //右移动
    rightMove() {
      if (this.multipleSelection.length == 0) {
        this.$notify.closeAll();
        this.$notify.error("没有可移动人员")
        return;
      }

      if (this.fzData.length > 0) {
        this.ryxxCheck();
      } else {
        this.$notify.closeAll();
        this.$notify.error("请先选择自定义分组后再进行操作")
      }
    },
    //人员信息重复校验
    ryxxCheck() {
      getFzList(this.fzData[this.radio].id).then(response => {
        var ryNames = "";
        var data = response.data.data;

        for (var a in data) {
          for (var b in this.multipleSelection) {
            if (data[a].ryCode == this.multipleSelection[b].ryCode) {
              ryNames += data[a].ryName + "(" + data[a].ryCode + ")、";
            }
          }
        }
        if (ryNames == "") {
          insertRymxbList(this.multipleSelection, this.fzData[this.radio].id).then(data => {
            if (data.data.code == 0) {
              this.$notify.closeAll();
              this.$notify.success('操作成功')
              this.multipleSelection = [];
              this.refreshby();
            } else {
              this.$notify.closeAll();
              this.$notify.error("操作失败")
            }
          }).catch(() => {
            this.$notify.closeAll();
            this.$notify.error("操作失败")
          });
        } else {
          this.$confirm(ryNames.substr(0, ryNames.length - 1) + '已存在，无法移动。', '提示', {
            showConfirmButton: false,
            cancelButtonText: '确定',
            type: 'warning'
          }).then(function () {
          }).catch(function (err) {
          })
        }
      })
    },
    handleSelectionChange(checkedNodes, checkedKeys) {
      var data = [];
      for (var a in checkedKeys.checkedNodes) {
        if (checkedKeys.checkedNodes[a].id != undefined) {
          data.push({
            jjDeptId: this.deptId,
            ryCode: checkedKeys.checkedNodes[a].ryCode,
            ryName: checkedKeys.checkedNodes[a].ryXm,
            ryZw: checkedKeys.checkedNodes[a].ryZhiwu,
            deptId: this.deptId
          });
        }
      }
      this.multipleSelection = data;
    },
    handleSelectionChangezdyfz(val) {
      this.multipleSelectionfz = val;
    },
    //获取奖金管理人机构
    getJiangJinJg() {
      getJiangJinBm().then(res => {
        if (res.data.data != null && res.data.data.length > 0) {
          this.deptId = res.data.data[0].deptId;
          this.deptName = res.data.data[0].deptName;

          this.fzbmData = res.data.data;
          this.ymLoad = false;
          this.refresh(0);
        } else {
          this.$notify.closeAll();
          this.ymLoad = true;
          //this.$notify.error("没有相关负责部门")
          //this.deptName = "无相关负责部门";
        }
      }).catch(err =>{
        this.ymLoad = true;
      });
      // 获取人员职级代码
      remoteDict("user_zj").then(response => {
        this.userZjOptions = response.data.data
      })
      // 获取员工子组代码
      remoteDict("subgroup").then(response => {
        this.userZzOptions = response.data.data
      })
    },

    //职务级别转换
    zjzh(value){
      for(var a in this.userZjOptions){
        if(this.userZjOptions[a].value == value){
          return this.userZjOptions[a].label;
        }
      }
    },

    //人员列表检索
    switchDepartment() {
      for (var a in this.fzbmData) {
        if (this.fzbmData[a].deptId == this.deptId) {
          this.deptId = this.fzbmData[a].deptId;
          this.deptName = this.fzbmData[a].deptName;
          this.refresh(1);

          break;
        }
      }
    },
    //增加外部人员
    addOtherPerson(e, item, index) {
      e.stopPropagation();

      this.queryXh(item.id, index);
      this.activeName = "";
      // this.activeName = this.radio
      this.perSelectionVisible = true;
      this.$nextTick(() => {
        this.$refs.perselection.init({jjDeptId: item.jjDeptId, id: item.id});
      });
    },
    //增加分组
    add_grouping(e, id) {
      e.stopPropagation();
      this.$nextTick(() => {
        this.$refs.tableForm.init(this.deptId, id);
      });
    },
    //父级操作后页面刷新
    refreshby() {
      this.activeName = this.radio
      this.fzData = [];
      this.ryData = [];
      this.filterText = "";

      getRyfzbList(this.deptId).then(res => {
        this.fzData = res.data.data;
        this.queryXh(this.fzData[this.radio].id, this.radio);
        this.getRyfzmxbList(0);
      });
    },
    //子级操作后页面刷新
    refresh(flag) {
      this.radio = 0;
      this.activeName = '';
      this.fzData = [];
      this.ryData = [];
      this.filterText = "";

      getRyfzbList(this.deptId).then(res => {
        this.fzData = res.data.data;
        this.getRyfzmxbList(flag);
      });
    },
    //获取页面数据附加方法
    getRyfzmxbList(flag) {
      getDeptList().then(resbm => {
        fetchListfy(this.deptId, this.dataForm).then(response => {
          var bm = resbm.data.data;

          for (var a in response.data.data) {
            var ry = response.data.data[a];
            this.$set(ry, 'deptCode', ry.ryCode)
            this.$set(ry, 'deptId', ry.ryCode)
            this.$set(ry, 'parentId', ry.rySjdwId)
            const s1 = ry.ryCode || ""
            const s2 = ry.ryZwjb || ""
            this.$set(ry, 'name', ry.ryXm + "(" + s1 + ")" + "【" + s2 + "】")
            bm.push(ry);
          }
          //this.ryData.length = 0
          this.ryData = this.getTree(bm, this.deptId, 1);
          this.idArr=[]
          this.ryData.forEach(m=>{
            if(flag==0){
              this.idArr.push(m.deptId)
            }else{

              if(m.children&&m.children.length>0){
                m.children.forEach(n=>{

                  if(n.children&&n.children.length>0){
                   n.children.forEach(v=>{
                      if(v.children&&v.children.length>0){
                        v.children.forEach(a=>{
                        //  console.log(JSON.stringify(a))
                          this.idArr.push(a.deptId)
                        })

                      }else{
                        this.idArr.push(v.deptId)
                      }
                    })

                  }else{
                    this.idArr.push(n.deptId)
                  }
                })
              }else{
                this.idArr.push(m.deptId)
              }

              this.idArr=this.quchong(this.idArr)
            }

        })
        }).catch(err => {
        })
      });
    },
    quchong(arr){

      for(var i = 0; i < arr.length-1; i++){
        //arr[i]=this.isString(arr[i])
            //console.log(Object.prototype.toString.call(arr[i]))
            for(var j = i+1; j < arr.length; j++){
             // arr[j]=this.isString(arr[j])
                if(arr[i]===arr[j]){
                    arr.splice(j,1);
                    j--;

                }
            }
        }

        return this.isString(arr);
    },
    isString(arr){
      var list=[]
      arr.forEach(obj=>{
        if(Object.prototype.toString.call(obj) === "[object String]"){
          list.push(obj)
        }
      })
      return list
    },
    //数据tree结构化
    getTree(bmlist, id, bz) {
      return bmlist.filter(v => {
        if (bz) {
          if (v.deptId === id) {
            return v
          }
        } else {
          if (v.parentId === id) {
            return v
          }
        }
      }).map(v => {
        const children = this.getTree(bmlist, v.deptId, 0);
        if (children.length) v.children = this.getTree(bmlist, v.deptId, 0);
        return v
      });
    },
    //行点击事件
    queryXh(id, index) {
      this.radio = index;
      this.dataListLoading = true
      getFzList(id).then(response => {
        this.$set(this.fzData[index], 'tableData', response.data.data);
        this.dataListLoading = false
      })
    },
    //去除行联动
    grouping(id, name) {
    },
    // 删除
    deleteHandle(e, id) {
      e.stopPropagation();

      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(id)
      }).then(data => {
        this.$notify.closeAll();
        this.$notify.success('删除成功')
        this.refresh(0)
      })
    }
  }
}
</script>
